<template>
  <div class="search">
    <!-- 顶部搜索 -->
    <van-search
      v-model="seachText"
      shape="round"
      background="#4fc08d"
      placeholder="请输入搜索关键词"
      @search="getSearchShop"
      @input="getProducts"
    />

    <!-- 最近搜索 -->
    <div class="zsearch">
      <div class="title">最近搜索</div>
      <van-tag
      v-for="(item, i) in oldsearchList"
      :key="i" color="#E9EBEC" size="large"
      @click="tagCklick(item)"
      text-color="#999">{{ item }}</van-tag>
    </div>

    <!-- 热门搜索 -->
    <div class="host">
      <div class="title">热门搜索</div>
      <van-tag
      v-for="(item, i) in hostsearch"
      :key="i" color="#E9EBEC" size="large"
      @click="tagCklick(item)"
      text-color="#999">{{ item }}</van-tag>
    </div>

    <!-- 搜索到的商品 -->
    <div class="shopbox" v-show="searchList.content">
      <shop :list="searchList.content || []" />
    </div>

    <!-- 空状态 -->
    <van-empty description="没有更多了，换个关键词搜索吧" v-show="!searchList.totalElements" />
  </div>
</template>

<script>
import shop from '@/components/shop'
import {
  hostsearch,
  getProducts,
} from '@/api/search'

export default {
  data() {
    return {
      hostsearch: [], // 热门搜索
      seachText: '', // 搜索关键字
      searchList: [], // 搜索列表
      timeout: null, // 节流
      oldsearchList: [], // 历史搜索列表
    }
  },
  created() {
    this.getOldSearch()
    this.getHostSearch()
  },
  methods: {
    // 获取热门搜索
    async getHostSearch() {
      const { data } = await hostsearch()
      this.hostsearch = data || []
    },

    // 获取搜索商品列表
    getProducts(e) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(async () => {
        const { data } = await getProducts(e)
        this.searchList = data || []
      }, 1500)
    },

    // 搜索商品列表
    getSearchShop(e) {
      // 保存历史搜索
      this.oldsearchList = [...new Set([e, ...this.oldsearchList])]
      localStorage.setItem('searchList', JSON.stringify(this.oldsearchList))
      this.$router.push({
        path: '/productList',
        query: { keyword: e }
      })
    },

    // 获取历史搜索列表
    getOldSearch() {
      this.oldsearchList = JSON.parse(localStorage.getItem('searchList')) || []
    },

    // 点击事件
    tagCklick(val) {
      this.seachText = val
      this.getSearchShop(val)
    },
  },
  components: {
    shop,
  }
}
</script>
<style lang="scss" scoped>
.zsearch, .host {
  // width: 100%;
  min-height: 80px;
  text-align: left;
  padding: 10px 20px;
  // background-color: pink;
  .title {
    font-size: 14px;
    font-weight: 550;
    margin-bottom: 10px;
  }
  .van-tag {
    margin-left: 10px;
    margin-bottom: 8px;
  }
}
.shopbox {
  // margin: 10px;
}
</style>